import { useState, useEffect } from 'react';
import { message } from 'antd';

// 系统配置类型
interface SystemConfig {
  platformName: string;
  platformVersion: string;
  platformDescription: string;
  maxTenants: number;
  defaultStorageQuota: number;
  apiRateLimit: number;
  allowTenantRegistration: boolean;
}

// 安全配置类型
interface SecurityConfig {
  passwordMinLength: number;
  passwordMaxLength: number;
  passwordExpireDays: number;
  requireComplexPassword: boolean;
  requireSpecialChars: boolean;
  passwordHistoryCheck: number;
  maxLoginAttempts: number;
  lockoutDuration: number;
  enableTwoFactor: boolean;
  enableCaptcha: boolean;
  allowedIpRanges: string;
  sessionTimeout: number;
  maxConcurrentSessions: number;
  sessionIdleTimeout: number;
  forceHttps: boolean;
  enableSessionProtection: boolean;
  allowRememberLogin: boolean;
}

// 权限模板类型
interface PermissionTemplate {
  id: string;
  name: string;
  description: string;
  type: 'admin' | 'user' | 'readonly';
  permissionCount: number;
  usageCount: number;
  createTime: string;
  updateTime: string;
  permissions?: string[];
}

// 系统统计类型
interface SystemStats {
  uptime: number;
  systemLoad: number;
  memoryUsage: number;
  diskUsage: number;
  activeTenants: number;
  totalUsers: number;
  todayRequests: number;
  successRate: number;
}

// 模拟数据
const mockSystemConfig: SystemConfig = {
  platformName: 'V3 Cloud Platform',
  platformVersion: '3.0.1',
  platformDescription: '新一代云原生多租户管理平台',
  maxTenants: 1000,
  defaultStorageQuota: 100,
  apiRateLimit: 10000,
  allowTenantRegistration: true,
};

const mockSecurityConfig: SecurityConfig = {
  passwordMinLength: 8,
  passwordMaxLength: 32,
  passwordExpireDays: 90,
  requireComplexPassword: true,
  requireSpecialChars: false,
  passwordHistoryCheck: 3,
  maxLoginAttempts: 5,
  lockoutDuration: 15,
  enableTwoFactor: false,
  enableCaptcha: true,
  allowedIpRanges: '',
  sessionTimeout: 30,
  maxConcurrentSessions: 3,
  sessionIdleTimeout: 15,
  forceHttps: true,
  enableSessionProtection: true,
  allowRememberLogin: false,
};

const mockPermissionTemplates: PermissionTemplate[] = [
  {
    id: '1',
    name: '平台超级管理员',
    description: '具有完整系统管理权限的模板',
    type: 'admin',
    permissionCount: 35,
    usageCount: 3,
    createTime: '2024-01-15T10:30:00Z',
    updateTime: '2024-01-20T15:45:00Z',
    permissions: ['platform:admin', 'tenant:create', 'tenant:update', 'tenant:delete', 'user:manage', 'system:config'],
  },
  {
    id: '2',
    name: '平台支持专员',
    description: '支持人员权限模板，可查看和协助处理问题',
    type: 'user',
    permissionCount: 15,
    usageCount: 8,
    createTime: '2024-01-10T09:15:00Z',
    updateTime: '2024-01-18T11:20:00Z',
    permissions: ['tenant:read', 'ticket:manage', 'log:read', 'monitor:read'],
  },
  {
    id: '3',
    name: '平台审计员',
    description: '仅具有查看和审计权限的用户模板',
    type: 'readonly',
    permissionCount: 8,
    usageCount: 5,
    createTime: '2024-01-12T14:20:00Z',
    updateTime: '2024-01-16T16:30:00Z',
    permissions: ['platform:read', 'log:read', 'audit:read', 'report:read'],
  },
  {
    id: '4',
    name: '租户管理员',
    description: '租户管理员的标准权限模板',
    type: 'admin',
    permissionCount: 20,
    usageCount: 156,
    createTime: '2024-01-08T16:20:00Z',
    updateTime: '2024-01-19T14:30:00Z',
    permissions: ['user:create', 'user:update', 'user:delete', 'role:manage', 'dept:manage', 'team:manage'],
  },
];

const mockSystemStats: SystemStats = {
  uptime: 45,
  systemLoad: 1.2,
  memoryUsage: 68.5,
  diskUsage: 45.2,
  activeTenants: 156,
  totalUsers: 2847,
  todayRequests: 156782,
  successRate: 99.2,
};

// 系统配置管理hook
export const useSystemConfig = () => {
  const [config, setConfig] = useState<SystemConfig>(mockSystemConfig);
  const [loading, setLoading] = useState(false);

  const loadConfig = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      setConfig(mockSystemConfig);
    } catch (error) {
      console.error('加载系统配置失败:', error);
      message.error('加载系统配置失败');
    } finally {
      setLoading(false);
    }
  };

  const updateConfig = async (newConfig: SystemConfig) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      setConfig(newConfig);
      message.success('系统配置保存成功');
    } catch (error) {
      message.error('保存失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const resetConfig = () => {
    setConfig(mockSystemConfig);
    message.info('已重置为默认配置');
  };

  useEffect(() => {
    loadConfig();
  }, []);

  return {
    config,
    loading,
    updateConfig,
    resetConfig,
    refresh: loadConfig,
  };
};

// 安全配置管理hook
export const useSecurityConfig = () => {
  const [config, setConfig] = useState<SecurityConfig>(mockSecurityConfig);
  const [loading, setLoading] = useState(false);

  const loadConfig = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      setConfig(mockSecurityConfig);
    } catch (error) {
      console.error('加载安全配置失败:', error);
      message.error('加载安全配置失败');
    } finally {
      setLoading(false);
    }
  };

  const updateConfig = async (newConfig: SecurityConfig) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      setConfig(newConfig);
      message.success('安全配置保存成功');
    } catch (error) {
      message.error('保存失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const resetConfig = () => {
    setConfig(mockSecurityConfig);
    message.info('已重置为默认配置');
  };

  useEffect(() => {
    loadConfig();
  }, []);

  return {
    config,
    loading,
    updateConfig,
    resetConfig,
    refresh: loadConfig,
  };
};

// 权限模板管理hook
export const usePermissionTemplates = () => {
  const [templates, setTemplates] = useState<PermissionTemplate[]>([]);
  const [loading, setLoading] = useState(false);

  const loadTemplates = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      setTemplates(mockPermissionTemplates);
    } catch (error) {
      console.error('加载权限模板失败:', error);
      message.error('加载权限模板失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadTemplates();
  }, []);

  return {
    templates,
    loading,
    refresh: loadTemplates,
  };
};

// 权限模板操作hook
export const usePermissionTemplateActions = () => {
  const [loading, setLoading] = useState(false);

  const createTemplate = async (data: Omit<PermissionTemplate, 'id' | 'createTime' | 'updateTime'>) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('权限模板创建成功');
    } catch (error) {
      message.error('权限模板创建失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateTemplate = async (id: string, data: Partial<PermissionTemplate>) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('权限模板更新成功');
    } catch (error) {
      message.error('权限模板更新失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteTemplate = async (id: string) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      message.success('权限模板删除成功');
    } catch (error) {
      message.error('权限模板删除失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const copyTemplate = async (id: string) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      message.success('权限模板复制成功');
    } catch (error) {
      message.error('权限模板复制失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    copyTemplate,
  };
};

// 系统统计hook
export const useSystemStats = () => {
  const [stats, setStats] = useState<SystemStats>(mockSystemStats);
  const [loading, setLoading] = useState(false);

  const loadStats = async () => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 300));
      // 模拟动态数据
      const dynamicStats = {
        ...mockSystemStats,
        systemLoad: Number((Math.random() * 2 + 0.5).toFixed(1)),
        memoryUsage: Number((Math.random() * 30 + 50).toFixed(1)),
        diskUsage: Number((Math.random() * 20 + 35).toFixed(1)),
        todayRequests: mockSystemStats.todayRequests + Math.floor(Math.random() * 1000),
        successRate: Number((99 + Math.random()).toFixed(1)),
      };
      setStats(dynamicStats);
    } catch (error) {
      console.error('加载系统统计失败:', error);
      message.error('加载系统统计失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadStats();
    // 每30秒刷新一次统计数据
    const interval = setInterval(loadStats, 30000);
    return () => clearInterval(interval);
  }, []);

  return {
    stats,
    loading,
    refresh: loadStats,
  };
};

// 导出类型
export type {
  SystemConfig,
  SecurityConfig,
  PermissionTemplate,
  SystemStats,
}; 